import { defineConfig, loadEnv } from 'vite'
import electron from 'vite-plugin-electron/simple'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers'
import tailwindcss from '@tailwindcss/vite'
import path from 'node:path'

export default ({ mode }: { mode: string }) =>
  defineConfig({
    plugins: [
      vue(),
      electron({
        main: {
          entry: 'electron/main.ts'
        },
        preload: {
          input: path.join(__dirname, 'electron/preload.ts')
        },
        renderer:
          process.env.NODE_ENV === 'test'
            ? // https://github.com/electron-vite/vite-plugin-electron-renderer/issues/78#issuecomment-2053600808
              undefined
            : {}
      }),
      AutoImport({
        imports: [
          'vue',
          {
            'naive-ui': [
              'useDialog',
              'useMessage',
              'useNotification',
              'useLoadingBar'
            ]
          }
        ]
      }),
      Components({
        resolvers: [NaiveUiResolver()]
      }),
      tailwindcss()
    ],
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler'
        }
      }
    },
    server: {
      host: '0.0.0.0',
      port: Number(getEnv(mode).VITE_PORT),
      open: JSON.parse(getEnv(mode).VITE_OPEN),
      proxy: {
        '/api': {
          target: getEnv(mode).VITE_API_URL,
          ws: true,
          changeOrigin: true,
          secure: false,
          // rewrite: (path) => path.replace(/^\/api/, '/api')
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, '.', './src')
      }
    }
  })

function getEnv(mode: string): Record<string, any> {
  return loadEnv(mode, process.cwd())
}
